package com.hotcode;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/25 15:23
 */
public class leecode39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new LinkedList<>();
        if (candidates.length == 0) {
            return res;
        }
        backtrace(candidates, target, 0, 0, res, new LinkedList<>());
        return res;

    }


    public void backtrace(int[] candidates, int target, int sum, int start, List<List<Integer>> res, LinkedList<Integer> oneAns) {
        if (sum == target) {
            res.add(new LinkedList<>(oneAns));
            return;
        }
        if (sum > target) {
            return;
        }


        for (int i = start; i < candidates.length; i++) {
            oneAns.add(candidates[i]);
            sum += candidates[i];
            backtrace(candidates, target, sum, i, res, oneAns);
            sum -= candidates[i];
            oneAns.removeLast();
        }
    }
}
